/** @file    FormSystemLogger.cpp
 *  @author  Alessandro Polo
 *  @version $Id: FormSystemLogger.cpp 2867 2010-08-07 20:44:51Z alex $
 *  @brief
 * File containing methods for the wosh::gui::FormSystemLogger class.
 * The header for this class can be found in FormSystemLogger.h, check that file
 * for class description.
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

 #include "FormSystemLogger.h"
 #include "ui_FormSystemLogger.h"
 #include <core/SystemLogger.h>

 #include <core/List.h>
 #include <QtGui/QInputDialog>
 #include <QtGui/QMessageBox>


using namespace std;
namespace wosh {
 namespace gui {

 WOSH_REGISTER(wosh::gui::FormSystemLogger, "wosh::gui::IWidgetGeneric", 1.0, _static_FormSystemLogger )
 WOSH_GUI_MAP(wosh::gui::FormSystemLogger, "wosh::SystemLogger", 0.0, _static_Map_FormSystemLogger )

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

FormSystemLogger::FormSystemLogger(QWidget *parent)
	: IWidgetGeneric(parent) {
	this->m_ui = new Ui::FormSystemLogger();
	this->m_ui->setupUi(this);

	IWidgetGeneric::setTargetURI(_SystemLogger_URI);
	buildMenus();

	// tab LogContexts [0]
	this->m_ui->tableViewContexts->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewContexts, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewContexts, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableViewContexts_ContextMenu(const QPoint&, const QModelIndex&)) );

	// tab LogHandlers [1]
	this->m_ui->tableViewHandlers->setMethodList(_SystemLogger_METHOD_list_handlers);
	this->m_ui->tableViewHandlers->getTableView()->setContextMenuPolicy(Qt::CustomContextMenu);
	connect(this->m_ui->tableViewHandlers, SIGNAL(postMessage(Message*)),this, SLOT(postMessage(Message*)) );
	connect(this->m_ui->tableViewHandlers, SIGNAL(tableContextMenuRequested(const QPoint&, const QModelIndex&)),this, SLOT(tableViewHandlers_ContextMenu(const QPoint&, const QModelIndex&)) );
	connect(this->m_ui->btnHandlerAdd, SIGNAL(clicked()), this, SLOT(btnHandlerAdd_clicked()));
	connect(this->m_ui->btnHandlerRemove, SIGNAL(clicked()), this, SLOT(btnHandlerRemove_clicked()));

 }

FormSystemLogger::~FormSystemLogger() {
	delete this->m_ui;
 }

void FormSystemLogger::changeEvent(QEvent *e) {
	QWidget::changeEvent(e);
	if ( e->type() == QEvent::LanguageChange )
		this->m_ui->retranslateUi(this);
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemLogger::refreshAll() {
	this->setWindowTitle( QString("System Logger [%1]").arg(this->getTargetURI().getKernelName().c_str()) );
	this->m_ui->tableViewContexts->refreshData();
	this->m_ui->tableViewHandlers->refreshData();
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemLogger::btnHandlerAdd_clicked() {
	bool ok;
	QString htype = QInputDialog::getText(this, tr("Add New Handler.."), tr("Handler Type:"), QLineEdit::Normal, "wosh::", &ok);
	if ( !ok || htype.isEmpty() )
		return;
	Variant* handler_type = new Variant( htype.toLatin1().data() );
	QString hproto = QInputDialog::getText(this, tr("Add New Handler [%1]..").arg(htype), tr("Handler Protocol:"), QLineEdit::Normal, "", &ok);
	if ( !ok || hproto.isEmpty() ) {
		executeRemoteMethod( _SystemLogger_METHOD_add_handler, handler_type );
		return;
	 }
	List* args = new List(2);
	args->push_back( handler_type );
	args->push_back<Variant>( hproto.toLatin1().data() );
	executeRemoteMethod( _SystemLogger_METHOD_add_handler, args );
 }

void FormSystemLogger::btnHandlerRemove_clicked() {
	Variant contextName = this->m_ui->tableViewHandlers->getCurrentItemAsVariantAtCol(0);
	if ( contextName.isEmpty() ) return;
	executeRemoteMethod( _SystemLogger_METHOD_remove_handler, contextName.clone() );
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemLogger::buildMenus() {
	this->menuContextTitle = new QAction(this);
	this->menuContextTitle->setEnabled(false);
	this->menuContextChangeHandler = new QAction(this);
	this->menuContextChangeHandler->setText(tr("&Change Handler.."));
	this->menuContextAddHandler = new QAction(this);
	this->menuContextAddHandler->setText(tr("&Add Handler.."));
	this->menuContext = new QMenu(this);
	this->menuContext->addAction(this->menuContextTitle);
	this->menuContext->addSeparator();
	this->menuContext->addAction(this->menuContextChangeHandler);
	this->menuContext->addAction(this->menuContextAddHandler);
	this->menuContext->addSeparator();

	this->menuHandlerTitle = new QAction(this);
	this->menuHandlerTitle->setEnabled(false);
	this->menuHandlerChangeProtocol = new QAction(this);
	this->menuHandlerChangeProtocol->setText(tr("Change &Protocol.."));
	this->menuHandlerUnLinkContexts = new QAction(this);
	this->menuHandlerUnLinkContexts->setText(tr("&UnLink Handler from Contexts.."));
	this->menuHandlerSetForUnLinkedContexts = new QAction(this);
	this->menuHandlerSetForUnLinkedContexts->setText(tr("&Set to UnLinked Contexts.."));
	this->menuHandlerReplaceHandler = new QAction(this);
	this->menuHandlerReplaceHandler->setText(tr("&Replace Handler.."));
	this->menuHandlerLinkContext = new QAction(this);
	this->menuHandlerLinkContext->setText(tr("&Link Context.."));
	this->menuHandler = new QMenu(this);
	this->menuHandler->addAction(this->menuHandlerTitle);
	this->menuHandler->addSeparator();
	this->menuHandler->addAction(this->menuHandlerChangeProtocol);
	this->menuHandler->addSeparator();
	this->menuHandler->addAction(this->menuHandlerUnLinkContexts);
	this->menuHandler->addAction(this->menuHandlerSetForUnLinkedContexts);
	this->menuHandler->addAction(this->menuHandlerReplaceHandler);
	this->menuHandler->addSeparator();
	this->menuHandler->addAction(this->menuHandlerLinkContext);

 }

void FormSystemLogger::tableViewContexts_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() || index.row() == 0 ) return;
	Variant contextName = this->m_ui->tableViewContexts->getCurrentItemAsVariantAtCol(0);
	this->menuContextTitle->setText( contextName.toString().c_str() );
	this->menuContextTitle->setIcon( GuiUtilities::createIconFor(LogContext::className()) );

	QAction* selected = this->menuContext->exec( globalPos );
	if ( selected == this->menuContextAddHandler ) {

	 }
	else if ( selected == this->menuContextChangeHandler ) {
	
	 }

 }
 
void FormSystemLogger::tableViewHandlers_ContextMenu( const QPoint& pos, const QModelIndex& index ) {
	QPoint globalPos = this->mapToGlobal(pos);
	if ( !index.isValid() || index.row() == 0 ) return;
	Variant handlerID = this->m_ui->tableViewHandlers->getCurrentItemAsVariantAtCol(0);
	Variant handlerType = this->m_ui->tableViewHandlers->getCurrentItemAsVariantAtCol(1);
	this->menuHandlerTitle->setText( QString("Handler#%1").arg(handlerID.toLong(0)) );
	this->menuHandlerTitle->setIcon( GuiUtilities::createIconFor(handlerType.toString()) );

	QAction* selected = this->menuHandler->exec( globalPos );
	if ( selected == this->menuHandlerUnLinkContexts ) {
		List* args = new List(2);
		args->push_back( handlerID.clone() );
		args->push_back<Variant>( 0 );
		executeRemoteMethod( _SystemLogger_METHOD_swap_handler, args ); // replace selected handler with NULL 
	 }
	else if ( selected == this->menuHandlerSetForUnLinkedContexts ) {
		List* args = new List(2);
		args->push_back<Variant>( 0 );
		args->push_back( handlerID.clone() );
		executeRemoteMethod( _SystemLogger_METHOD_swap_handler, args ); // replace NULL handler with selected
	 }
	else if ( selected == this->menuHandlerReplaceHandler ) {
#if QT_VERSION >= 0x040601
		long handle_new_id = QInputDialog::getInt(this, tr("Update of Context using Handler#%1..").arg(handlerID.toLong(0)), tr("New Handler ID:"), 0 );
#else
		bool ok;
		QString idStr = QInputDialog::getText(this, tr("Set Handler#%1 for Context..").arg(handlerID.toLong(0)), tr("New Handler ID:"), QLineEdit::Normal, "0", &ok);
		long handle_new_id = idStr.toLong();
#endif
		if ( handle_new_id == 0 )
			return;
		List* args = new List(2);
		args->push_back( handlerID.clone() );
		args->push_back<Variant>( handle_new_id );
		executeRemoteMethod( _SystemLogger_METHOD_swap_handler, args ); // replace selected handler with dialog-input
	 }
	else if ( selected == this->menuHandlerLinkContext ) {
		bool ok;
		QString contextName = QInputDialog::getText(this, tr("Set Handler#%1 for Context..").arg(handlerID.toLong(0)), tr("Log-Context Name:"), QLineEdit::Normal, this->m_ui->tableViewContexts->getCurrentItemAsVariantAtCol(0).toString().c_str(), &ok);
		if ( !ok || contextName.isEmpty() )
			return;
		List* args = new List(2);
		args->push_back( handlerID.clone() );
		args->push_back<Variant>( contextName.toLatin1().data() );
		executeRemoteMethod( _SystemLogger_METHOD_link_handler, args ); // set selected handler to input context
	 }
	else if ( selected == this->menuHandlerChangeProtocol ) {
		Variant handlerProtocol = this->m_ui->tableViewHandlers->getCurrentItemAsVariantAtCol(3);
		bool ok;
		QString hProto = QInputDialog::getText(this, tr("Change Protocol of %1..").arg(handlerID.toLong(0)), tr("Protocol:"), QLineEdit::Normal, handlerProtocol.toString().c_str(), &ok);
		if ( !ok || hProto.isEmpty() )
			return;
		List* args = new List(2);
		args->push_back( handlerID.clone() );
		args->push_back<Variant>( hProto.toLatin1().data() );
		executeRemoteMethod( _SystemLogger_METHOD_edit_handler, args );
	 }
	
 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////

void FormSystemLogger::busMessage( const Message& message, const Bus* ) {
	if ( message.isEmpty() || !message.getContent()->isResponse() ) return;
	if ( !isMessageForMeOrFromTarget(message) ) return;
	const wosh::Response* response = message.getContent()->asResponse();

	this->m_ui->tableViewContexts->evalResponse(response);
	this->m_ui->tableViewHandlers->evalResponse(response);

	if ( !promptMethodResponse(message) ) {
		if ( response->getMethod() == _SystemLogger_METHOD_swap_handler ) {
			QMessageBox::information(this, tr("Log Handlers"), tr("Handlers swapped (re-linked) successfully!") );
		 }
	 }

 }

//////////////////////////////////////////////////////////////////////////////////////////////////////////////

 }; // namespace gui
}; // namespace wosh
